<template>
  <div class="bg-light">
    <!-- 头部 -->
    <div class="header d-flex align-items-center">
      <router-link :to="`/english/weekTestExam?noticeId=${noticeId}&examPaperId=${examPaperId}`" @click.prevent="submitAnswers" class="text-dark">
        <i class="bi bi-chevron-left fs-4"></i>
      </router-link>
      <h5 class="mb-0 mx-auto"> 阅读 Text {{ textNumber }}</h5>
      <i class="bi bi-bookmark text-muted"></i>
    </div>

<!--    &lt;!&ndash; 阅读工具栏 &ndash;&gt;-->
<!--    <div class="reading-tools d-flex justify-content-around">-->
<!--      <button class="tool-btn" id="translateBtn" @click="toggleTranslation">-->
<!--        <i class="bi bi-translate"></i> 全文翻译-->
<!--      </button>-->
<!--      <button class="tool-btn" id="difficultBtn" @click="toggleDifficult">-->
<!--        <i class="bi bi-braces"></i> 长难句解析-->
<!--      </button>-->
<!--      <button class="tool-btn" id="vocabBtn" @click="toggleVocab">-->
<!--        <i class="bi bi-book"></i> 生词本-->
<!--      </button>-->
<!--    </div>-->

    <!-- 阅读内容 -->
    <div class="reading-content" v-if="readingData.readingContent">
      <div v-for="(paragraph, index) in readingData.readingContent" :key="index" class="paragraph" :data-paragraph-id="index">
        <span class="paragraph-number">[{{ index + 1 }}]</span>
        <div class="english-text">
                    <span v-for="word in paragraph.englishText" class="clickable-word"
                          :class="{ 'new-word': word.newWord }"
                          :data-word="word.word"
                          :data-phonetic="word.phonetic"
                          :data-meaning="word.meaning">{{ word.word }}</span>
        </div>
        <div class="chinese-text">{{ paragraph.chineseText }}</div>
<!--        <div v-for="sentence in paragraph.sentenceAnalysis" class="sentence-analysis"-->
<!--             :id="'analysis-' + sentence.id">-->
<!--          <div class="analysis-title">长难句解析</div>-->
<!--          <div class="analysis-content">-->
<!--            <div class="structure-analysis">-->
<!--              <p><strong>句子结构：</strong></p>-->
<!--              <p>主干：{{ sentence.structure.main }}</p>-->
<!--              <p>并列谓语：</p>-->
<!--              <ul>-->
<!--                <li v-for="predicate in sentence.structure.predicates">{{ predicate }}</li>-->
<!--              </ul>-->
<!--              <p>目的状语：{{ sentence.structure.purpose }}</p>-->
<!--            </div>-->
<!--            <div class="translation-result">-->
<!--              <p><strong>译文：</strong></p>-->
<!--              <p>{{ sentence.translation }}</p>-->
<!--            </div>-->
<!--          </div>-->
<!--        </div>-->
        <div class="sentence-analysis" :id="'analysis-' + index">
          <!-- 解析内容会动态插入到这里 -->
        </div>
      </div>
    </div>

    <!-- 题目部分 -->
    <div class="question-section" v-if="readingData.questions">
      <div v-for="(question, questionIndex) in readingData.questions" :key="questionIndex" class="question">
        <p><strong>{{ question.qtitle }}</strong></p>
        <div v-for="(option, optionIndex) in question.item" :key="option.prefix"  class="option-item"
           @click.prevent="selectAnswer(questionIndex, optionIndex,option.prefix)">
          {{ option.prefix }}. {{ option.content }}
        </div>
      </div>
    </div>

    <!-- 底部工具栏 -->
    <div class="bottom-tools">
      <div>
        <button class="btn btn-outline-primary btn-sm me-2"
                @click="prevQuestion"
                :disabled="textNumber === 1">上一篇</button>
        <button class="btn btn-outline-primary btn-sm"
                @click="nextQuestion"
                :disabled="textNumber === totalQuestions">下一篇</button>
      </div>
      <div>
<!--        <button class="btn btn-primary" @click="goToAnalysis">答案解析</button>-->
      </div>
    </div>
  </div>
</template>

<script>
import http from "@/router/http";
import router from "@/router";
import {moduleTypeDict} from "@/router/dict";

export default {
  name: 'EnglishReadingTextView',
  data() {
    return {
      examPaperId: null,
      noticeId: null,
      articleId: null,
      totalQuestions: 4, // 总题目数
      selectedYear: null,
      textNumber: null, // 阅读内容
      readingData: {}, // 用于存储从后端获取的整个阅读相关数据
      isLoading: true, // 表示数据是否正在加载的状态，初始为 true
      selectedAnswers: {}, // 用于存储用户选择的答案，以题目编号为键，答案值为值
      userAnswers: [],
      wordTooltip: null,
      analysisData: [],
      vocabList: [],
      // 生词本列表
      currentWord: {
        word: '',
        phonetic: '',
        meaning: '',
        isNewWord: false,
        collected: false
      },
      showVocab: false, // 添加这个来跟踪生词本模式状态
      startTime: 0, // 记录答题开始时间（毫秒数）
      totalTimeSpent: 0, // 累计答题时间（毫秒数）
      isWordClickProcessing: false,
      prevQuestionEventBound: false, // 标记上一题切换时是否已绑定事件
      nextQuestionEventBound: false, // 标记下一题切换时是否已绑定事件
      clickEventsBound: false,
    }
  },
  beforeRouteEnter(to, from, next) {
    // 在进入路由前，将组件实例的属性设置为false，表示未绑定点击事件
    to.meta.wordClickEventBound = false;
    next();
  },
  beforeRouteLeave(to, from, next) {
    // 在离开当前路由时，获取当前组件实例（通过vm参数），并移除已经绑定的点击事件（如果有）
    const vm = this;
    const removeClickEvent = function () {
      document.removeEventListener('click', vm.handleWordClickWrapper);
    };
    removeClickEvent();
    next();
  },
  created() {
    this.textNumber = this.$route.query.text;
    this.startTime = Date.now();
    this.examPaperId = this.$route.query.examPaperId;
    this.noticeId = this.$route.query.noticeId;
  },
  methods: {
    selectAnswer(questionIndex, optionIndex,optionPrefix) {
      const questions = document.querySelectorAll('.question');
      const currentQuestion = questions[questionIndex];
      const options = currentQuestion.querySelectorAll('.option-item');
      options.forEach(opt => {
        opt.classList.remove('selected');
      });
      const selectedOption = options[optionIndex];
      if (selectedOption) {
        selectedOption.classList.add('selected');
      }
      this.selectedAnswers[questionIndex] = optionIndex;
      const existingIndex = this.userAnswers.findIndex(item => item.index === questionIndex);
      if(existingIndex > -1){
        this.userAnswers[existingIndex].value = optionPrefix;
      }else{
        this.userAnswers.push({
          index: questionIndex,
          value: optionPrefix
        })
      }
    },
    async fetchReadingData() {
      try {
        const moduleType = moduleTypeDict.find(item => item.code === 'ydlj').name;
        const params = {
          examPaperId: this.examPaperId,
          subjectName: 'english',
          moduleType: moduleType,
          currentQuestionIndex: this.textNumber
        }
        this.readingData = {}
        const response = await http.get('/student/question/getQuestionInfoForEnglish', {params: params}); // 假设后端获取阅读数据的接口地址，需根据实际情况修改
        const data = response.data
        if (!data || !data.response) {
          console.error('获取阅读数据失败:', data.message);
          alert("暂无数据，请稍后再试");
          router.push("/english/weekTestExam?noticeId="+this.noticeId+"&examPaperId="+this.examPaperId);
          this.isLoading = false;
          return;
        }
        this.readingData = data.response;
        this.textNumber = data.response.currentQuestionIndex;
        this.examPaperId = data.response.examPaperId;
        this.articleId = data.response.articleId;
        this.vocabList = data.response.vocabList || [];
        this.analysisData = data.response.nalysisTextList || [];
        this.isLoading = false;
      } catch (error) {
        console.error('获取阅读数据失败:', error);
        this.isLoading = false;
      }
    },
    prevQuestion() {
      if (this.textNumber > 1) {
        this.submitAnswers();
        this.textNumber--;
        this.userAnswers = []
        this.selectedAnswers = {}
        this.fetchReadingData().then(() => {
          if (!this.prevQuestionEventBound) {
            const questions = document.querySelectorAll('.question');
            questions.forEach((question, index) => {
              const selectedOptionIndex = this.selectedAnswers[index];
              if (selectedOptionIndex !== undefined) {
                const options = question.querySelectorAll('.option');
                const optionElement = options[selectedOptionIndex];
                if (optionElement) {
                  optionElement.classList.add('selected');
                }
              }
            });
            this.prevQuestionEventBound = true;
          }
        });
      }
    },
    nextQuestion() {
      if (this.textNumber < this.totalQuestions) {
        this.submitAnswers();
        this.textNumber++;
        this.userAnswers = []
        this.selectedAnswers = {}
        this.fetchReadingData().then(() => {
          if (!this.nextQuestionEventBound) {
            const questions = document.querySelectorAll('.question');
            questions.forEach((question, index) => {
              const selectedOptionIndex = this.selectedAnswers[index];
              if (selectedOptionIndex !== undefined) {
                const options = question.querySelectorAll('.option');
                const optionElement = options[selectedOptionIndex];
                if (optionElement) {
                  optionElement.classList.add('selected');
                }
              }
            });
            this.nextQuestionEventBound = true;
          }
        });
      }
    },
    async submitAnswers() {
      try {
        const currentTime = Date.now(); // 获取当前时间（毫秒数）
        this.totalTimeSpent += currentTime - this.startTime; // 累计答题时间
        const submitParentData = {
          questionId: this.readingData.questionId,
          examPaperId: this.examPaperId,
          totalTimeSpent: this.totalTimeSpent,
          resource: 1,
          userAnswer: this.userAnswers,
          isTest: true
        }

        // 发送POST请求将答题数据提交到后端
        const response = await http.post('/student/answer/submitAnswerForEnglish', submitParentData);
        if (response.status === 200) {
          console.log('答题数据提交成功');
          // router.push('/english/exam?year='+this.selectedYear);
          // 可以根据业务需求进行其他操作，比如提示用户提交成功，跳转到特定页面等
        } else {
          console.error('答题数据提交失败');
          // router.push('/english/exam?year='+this.selectedYear);
          // 同样可根据业务需求进行相应提示等操作
        }
      } catch (error) {
        console.error('提交答题数据出现错误:', error);
      }
    },
  },
  mounted() {
    this.fetchReadingData();
  },
  beforeDestroy() {
    // 清理工作
    if (this.wordTooltip && this.wordTooltip.parentNode) {
      this.wordTooltip.parentNode.removeChild(this.wordTooltip)
    }
  },
}
</script>

<style>
.translation-error {
  text-align: center;
  padding: 10px;
  color: #ff4444;
}
.option-item {
  background: white;
  padding: 15px;
  margin-bottom: 10px;
  border-radius: 10px;
  cursor: pointer;
}

.option-item.selected {
  background: #40e0d0;
  color: white;
}
.clickable-word {
  margin-right: 4px; /* 根据实际需要调整间距值，这里设置为10px，可自行更改 */
  /* 或者使用 padding 属性来增加间距，例如： */
  /* padding: 0 5px; */
}
.new-word {
  margin-right: 10px;
  /* 同样也可以添加 padding 属性，如：padding: 0 5px; */
}
.english-text {
  word-spacing: 8px; /* 设置单词间距为8px，可按需修改 */
}
body {
  background-color: #f0f9f9;
}

.header {
  padding: 15px;
  background: white;
  position: sticky;
  top: 0;
  z-index: 1000;
}

.reading-tools {
  background: white;
  padding: 10px;
  border-bottom: 1px solid #eee;
}

.tool-btn {
  border: none;
  background: none;
  color: #666;
  padding: 5px 15px;
  font-size: 0.9rem;
  cursor: pointer;
}

.tool-btn.active {
  color: #40e0d0;
  font-weight: bold;
}

.reading-content {
  background: white;
  padding: 20px;
  line-height: 1.8;
}

.paragraph {
  margin-bottom: 20px;
  position: relative;
}

.paragraph-number {
  position: absolute;
  left: -25px;
  color: #999;
  font-size: 0.8rem;
}

.question-section {
  margin-top: 15px;
  padding: 20px;
}

.question {
  margin-bottom: 25px;
}


.bottom-tools {
  position: fixed;
  bottom: 0;
  width: 100%;
  background: white;
  padding: 10px 20px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.translation-panel {
  display: none;
  background: white;
  padding: 15px;
  margin-top: 10px;
  border-radius: 8px;
  color: #666;
}

.chinese-text {
  display: none;
  color: #666;
  background: #f8f9fa;
  padding: 10px 15px;
  margin-top: 10px;
  border-left: 3px solid #40e0d0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.chinese-text.show {
  display: block;
  opacity: 1;
}

/* 长难句相关样式 */
.difficult-sentence {
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: inline-block;
}

.difficult-sentence.highlight {
  background-color: rgba(64, 224, 208, 0.1);
  border-radius: 4px;
  padding: 2px 4px;
}

.sentence-analysis {
  display: none;
  background: #f8f9fa;
  padding: 15px;
  margin: 10px 0;
  border-radius: 8px;
  border-left: 3px solid #40e0d0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.sentence-analysis.show {
  display: block;
  opacity: 1;
}

.analysis-title {
  color: #40e0d0;
  font-weight: bold;
  margin-bottom: 10px;
}

.structure-analysis {
  margin: 10px 0;
  padding: 10px;
  background: #fff;
  border-radius: 6px;
}

.translation-result {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px dashed #ddd;
}

/* 生词相关样式 */
.new-word {
  cursor: pointer;
  transition: all 0.3s ease;
}

.new-word.highlight {
  background-color: #FFE4B5;
  border-radius: 3px;
  padding: 0 2px;
}

.word-tooltip {
  position: absolute;
  background: white;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 300px;
  z-index: 1000;
  display: none;
}

.word-tooltip.show {
  display: block;
}

.word-phonetic {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 5px;
}

.word-meaning {
  border-top: 1px solid #eee;
  padding-top: 5px;
  margin-top: 5px;
}

.word-type {
  color: #40e0d0;
  font-weight: bold;
  margin-right: 5px;
}

/* 单词点击相关样式 */
.word-clickable {
  cursor: pointer;
  padding: 0 2px;
  border-radius: 3px;
  transition: background-color 0.2s;
}

.word-clickable:hover {
  background-color: rgba(64, 224, 208, 0.1);
}

.word-clickable.highlighted {
  background-color: rgba(64, 224, 208, 0.2);
}

.tooltip-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.collect-word-btn {
  background: #40e0d0;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9em;
  cursor: pointer;
}

.collect-word-btn:hover {
  background: #3bcdc0;
}

.collect-word-btn.collected {
  background: #999;
}

.loading-phonetic,
.loading-meaning {
  color: #999;
  font-style: italic;
  font-size: 0.9em;
}

.english-text {
  cursor: default;
  user-select: text;
  line-height: 1.8;
}

/* 让所有英文单词可点击 */
.english-text span,
.english-text {
  cursor: pointer;
}

.english-text span:hover,
.english-text:hover {
  background-color: transparent;
}

/* 添加新的单词样式 */
.clickable-word {
  cursor: pointer;
  padding: 0 1px;
  border-radius: 2px;
  transition: all 0.2s ease;
}

.clickable-word:hover {
  background-color: rgba(64, 224, 208, 0.1);
}

/* 确保新单词和预设生词样式一致 */
.new-word,
.clickable-word {
  display: inline-block;
}

.new-word.highlight {
  background-color: #FFE4B5;
  border-radius: 3px;
  padding: 0 2px;
}

/* 修改长难句相关样式 */
.difficult-sentence {
  cursor: pointer;
  transition: background-color 0.3s ease;
  display: inline-block; /* 确保长难句可以正确显示 */
}

.difficult-sentence.highlight {
  background-color: rgba(64, 224, 208, 0.1);
  border-radius: 4px;
  padding: 2px 4px;
}

/* 确保长难句内的单词不会被分开点击 */
.difficult-sentence .clickable-word {
  cursor: inherit;
  padding: 0;
  border-radius: 0;
  transition: none;
}

.difficult-sentence .clickable-word:hover {
  background-color: transparent;
}
.analysis-loading {
  text-align: center;
  padding: 20px;
  color: #666;
}

.analysis-error {
  text-align: center;
  padding: 20px;
  color: #ff4444;
}

.structure-analysis p {
  margin: 8px 0;
}

.structure-analysis ul {
  margin: 8px 0;
  padding-left: 20px;
  list-style-type: disc;
}

.structure-analysis li {
  margin: 4px 0;
  color: #666;
}

.translation-result p {
  margin: 8px 0;
  line-height: 1.6;
}

.translation-result p strong {
  color: #40e0d0;
}

.analysis-section {
  margin: 15px 0;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.analysis-section strong {
  color: #40e0d0;
  font-size: 1.1em;
}

.analysis-value {
  margin-top: 10px;
  font-family: monospace;
  font-size: 14px;
  line-height: 1.5;
}

.json-item {
  margin: 4px 0;
  padding-left: 16px;
}

.json-key {
  color: #0066cc;
  font-weight: 500;
}

.json-value {
  margin-left: 8px;
}

.json-array {
  margin-left: 16px;
}

.json-array-item {
  margin: 4px 0;
  padding-left: 8px;
  border-left: 2px solid #eee;
}

.json-primitive {
  color: #444;
}
</style>